import {
  createStore
} from 'vuex'
import Axios from 'axios'
import router from '../router/index'
import { notification } from 'ant-design-vue';

export default createStore({
  state: {
    //websocket实例
    socket: null,
    // 客户信息
    cusInfoList: [


    ],

    //聊天记录
    messageLog: [

    ],
    //当前对话客户id
    currCusInfo:{
        cusId:'',
        cusNackName:'',
        cusAvatar:'',
        tel:'',
        lookPro:'',
        position:'',
        cusSex:'',
        rectangle:''
    },
    //药品信息
    proInfo:{

    }

  },
  mutations: {
    //添加聊天记录
    messageLogChange(state, messages) {
      state.messageLog = messages
    },
    async currCusIdChange(state,index){
      state.currCusInfo=state.cusInfoList[index]

      state.proInfo= await  Axios.get('https://www.huangshen.work:666/YaoShopApi/common/product/get', {
        params: {
          proId:state.currCusInfo.lookPro
        }
      })
      .then((response)=> {
         return response.data.data
      })
      .catch(function (error) {
        console.log(error);
      });
 

    },


    //删除客户
    cusInfoListDel() {

    },
    //创建websocket实例
    init: function (state ,url) {

      if (typeof WebSocket === "undefined") {
        alert("您的浏览器不支持socket");
      } else {
        // 实例化socket
        state.socket = new WebSocket(url);
        // 监听socket连接
        state.socket.onopen = function () {
          console.log("socket连接成功")
        }
        // 监听socket错误信息
        state.socket.onerror = function () {
          console.log("连接错误")
        }
        // 监听socket消息
        state.socket.onmessage =  async function (msg) {

   
          //收到新消息 转为对象格式
          const message = JSON.parse(msg.data)
          notification['info']({
            message: '顾客提问',
            description:message.msg,
            onClick:()=>{
              router.push("/home/Message/Service" );
              }
          });

          let isInclould = false;

          for (let index = 0; index < state.cusInfoList.length; index++) {
            const element = state.cusInfoList[index];
            if (element.cusId == message.sendId) {
              state.cusInfoList[index].unread+=1;//已经存在于对话列表 收到新消息 设置未读

              if(state.currCusInfo.cusId==message.sendId){
                //如果是正在对话的客户 消息放入聊天记录
                state.messageLog.push(message)
                state.currCusInfo.lookPro=message.proId
              }
              isInclould = true;
              break;
            }

          }
          if (!isInclould) {
            let c={}
            // 客服队列中不存在这个客户 加入服务客户队列设置未读
             c= await  Axios.get('https://www.huangshen.work:666/YaoShopApi/admin/customer/get', {
              params: {
                cusId:message.sendId
              }
            })
            .then((response)=> {
               return response.data.data
            })
            .catch(function (error) {
              console.log(error);
            });
            
            let cus = {
              unread:1,//未读消息
              cusId: message.sendId,
              cusAvatar: c.cusAvatar, //头像
              position: message.position,
              rectangle:message.rectangle,
              cusNackName: c.cusNickname,
              cusSex: c.cusGender, //性别
              lookPro: message.proId,
            }
            state.cusInfoList.push(cus)
          }


        }
        state.socket.onclose = function () {
          console.log("socket已经关闭")
        }
      }
    },
    //发送消息
    send: function (state, msg) {
 
      state.socket.send(JSON.stringify(msg))
      const data = new Date()
      let year = data.getFullYear()
      let month = data.getMonth()
      let day = data.getDate()
      let hours = data.getHours()
      let minutes = data.getMinutes()
      let seconds = data.getSeconds()
      msg.sendTime = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" +seconds
      state.messageLog.push(msg)
      
      for (let index = 0; index < state.cusInfoList.length; index++) {
        const element = state.cusInfoList[index];
        if (element.cusId == msg.receiveId) {
          state.cusInfoList[index].unread=0;//将未读消息 设置为0
          break;
        }

      }
    },

    //清空未读消息
    clearUnread(state , uid){
      for (let index = 0; index < state.cusInfoList.length; index++) {
        const element = state.cusInfoList[index];
        if (element.cusId == uid) {
          state.cusInfoList[index].unread=0;//将未读消息 设置为0
          break;
        }
      }
    }
  },
  actions: {
    getMessageLog(context, args) {

      context.commit('clearUnread', args.split(",")[0])
      context.commit('currCusIdChange', args.split(",")[2])

      Axios.get('https://www.huangshen.work:666/YaoShopApi/common/chat/messageRecord', {
          params: {
            uid: args.split(",")[0],
            storeId: args.split(",")[1]
          }
        })
        .then(function (response) {
          context.commit('messageLogChange', response.data.data)
        })
        .catch(function (error) {
          console.log(error);
        });
    }
  },
  modules: {}
})